package com.ihrm.system.service;

import com.ihrm.common.entity.ResultCode;
import com.ihrm.common.exception.CommonException;
import com.ihrm.common.utils.BeanMapUtils;
import com.ihrm.common.utils.IdWorker;
import com.ihrm.common.utils.PermissionConstants;
import com.ihrm.domain.system.*;
import com.ihrm.system.dao.PermissionApiDao;
import com.ihrm.system.dao.PermissionDao;
import com.ihrm.system.dao.PermissionMenuDao;
import com.ihrm.system.dao.PermissionPointDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.naming.Name;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @auther chongxiongwei
 * @create 2020-04-20-11:13
 */
@Service
@Transactional
public class PermissionService {

    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private PermissionMenuDao permissionMenuDao;
    @Autowired
    private PermissionPointDao permissionPointDao;
    @Autowired
    private PermissionApiDao permissionApiDao;


    /**
     * 保存权限
     */
    public void save(Map<String,Object> map) throws Exception{
        // 设置主键的值
        String id = idWorker.nextId()+"";
        //1. 通过map构造permission对象
        Permission permission = BeanMapUtils.mapToBean(map,Permission.class);
        permission.setId(id);
        //2. 根据类型构造不同的资源对象（菜单，按钮，api）
        int type = permission.getType();
        switch (type){
            case PermissionConstants.PY_MENU:
                PermissionMenu permissionMenu = BeanMapUtils.mapToBean(map,PermissionMenu.class);
                permissionMenu.setId(id);
                permissionMenuDao.save(permissionMenu);
                break;

            case PermissionConstants.PY_POINT:
                PermissionPoint permissionPoint = BeanMapUtils.mapToBean(map,PermissionPoint.class);
                permissionPoint.setId(id);
                permissionPointDao.save(permissionPoint);
                break;
            case PermissionConstants.PY_API:
                PermissionApi permissionApi = BeanMapUtils.mapToBean(map,PermissionApi.class);
                permissionApi.setId(id);
                permissionApiDao.save(permissionApi);
                break;
            default:
                throw new CommonException(ResultCode.FAIL);
        }
        //3. 保存权限
        permissionDao.save(permission);

    }

    /**
     * 更新权限
     */
    public void update(Map<String,Object> map) throws Exception {
        Permission permission = BeanMapUtils.mapToBean(map,Permission.class);
        //1.通过传递的权限ID查询权限
        Permission temp = permissionDao.findById(permission.getId()).get();
        temp.setName(permission.getName());
        temp.setCode(permission.getCode());
        temp.setDescription(permission.getDescription());
        temp.setEnVisible(permission.getEnVisible());
        //2. 根据类型构造不同的资源对象（菜单，按钮，api）
        int type = permission.getType();
        switch (type){
            case PermissionConstants.PY_MENU:
                PermissionMenu permissionMenu = BeanMapUtils.mapToBean(map,PermissionMenu.class);
                permissionMenu.setId(permission.getId());
                permissionMenuDao.save(permissionMenu);
                break;

            case PermissionConstants.PY_POINT:
                PermissionPoint permissionPoint = BeanMapUtils.mapToBean(map,PermissionPoint.class);
                permissionPoint.setId(permission.getId());
                permissionPointDao.save(permissionPoint);
                break;
            case PermissionConstants.PY_API:
                PermissionApi permissionApi = BeanMapUtils.mapToBean(map,PermissionApi.class);
                permissionApi.setId(permission.getId());
                permissionApiDao.save(permissionApi);
                break;
            default:
                throw new CommonException(ResultCode.FAIL);
        }
        //3. 保存权限
        permissionDao.save(permission);
    }

    /**
     * 根据ID删除权限
     * 1.删除权限
     * 2.删除权限对应的资源
     */
    public void delete(String id) throws CommonException {

        //1.通过传递的权限ID查询权限
        Permission permission = permissionDao.findById(id).get();
        //2. 根据类型删除不同的资源对象（菜单，按钮，api）
        int type = permission.getType();
        switch (type){
            case PermissionConstants.PY_MENU:
                permissionMenuDao.deleteById(id);
                break;
            case PermissionConstants.PY_POINT:
                permissionPointDao.deleteById(id);
                break;
            case PermissionConstants.PY_API:
                permissionApiDao.deleteById(id);
                break;
            default:
                throw new CommonException(ResultCode.FAIL);
        }
        //3. 删除权限
        permissionDao.delete(permission);
    }

    /**
     * 根据ID查询权限
     *   1.查询权限
     *   2.根据权限查询资源
     *  返回map集合
     */
    public Map findById(String id) throws CommonException {
        Permission permission = permissionDao.findById(id).get();
        int type = permission.getType();
        Object object = null;
        if(type == PermissionConstants.PY_MENU){
            object = permissionMenuDao.findById(id).get();
        }else if(type == PermissionConstants.PY_POINT){
            object = permissionPointDao.findById(id).get();
        }else if(type == PermissionConstants.PY_API){
            object = permissionApiDao.findById(id).get();
        }else {
            throw new CommonException(ResultCode.FAIL);
        }
        Map<String,Object> map= BeanMapUtils.beanToMap(object);
        map.put("name", permission.getName());
        map.put("type",permission.getType());
        map.put("code",permission.getCode());
        map.put("description",permission.getDescription());
        map.put("pid",permission.getId());
        map.put("enVisible",permission.getEnVisible());
        return map;
    }

    /**
     * 查询所有权限
     */
    public List<Permission> findAll(Map<String,Object> map){

        // 1.需要查询的条件
        Specification<Permission> specification = new Specification<Permission>() {
            @Override
            public Predicate toPredicate(Root<Permission> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> list = new ArrayList<>();
                // 根据请求的父id是否为空构造查询条件
                if(!StringUtils.isEmpty(map.get("pid"))){
                    list.add(criteriaBuilder.equal(root.get("pid").as(String.class),(String)map.get("pid")));
                }
                // 根据请求的enVisible 是否为空构造查询条件
                if(!StringUtils.isEmpty(map.get("enVisible"))){
                    list.add(criteriaBuilder.equal(root.get("enVisible").as(String.class),(String)map.get("enVisible")));
                }
                // 根据请求的 hasdept来判断  0未分配 （departmentId = null） 1已分配 departmentId != null）
                if(!StringUtils.isEmpty(map.get("type"))){
                    String type = (String) map.get("type");
                    CriteriaBuilder.In<Object> in = criteriaBuilder.in(root.get("type"));
                    if("0".equals(type)){
                        in.value(1).value(2);
                    }else{
                        in.value(Integer.parseInt(type));
                    }
                    list.add(in);
                }
//                list.toArray(new Predicate[list.size()])
                return criteriaBuilder.and(list.toArray(new Predicate[list.size()]));
            }
        };
        return permissionDao.findAll(specification);
    }

}
